package com.macro.mall.portal.service.impl;

import java.util.Date;

import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.macro.mall.mapper.BmsMpTokenMapper;
import com.macro.mall.model.BmsMpToken;
import com.macro.mall.portal.service.MpTokenService;
import com.macro.mall.portal.util.MpConstant;

import cn.hutool.core.convert.Convert;

@Service
public class MpTokenServiceImpl implements MpTokenService {

    @Autowired
    private BmsMpTokenMapper baseMapper;

    @Override
    public String getAccessToken(String appId, String appSecret) {
        BmsMpToken mpToken = baseMapper.getByAppId(appId);
        Date endDate = new Date();
        if (mpToken == null || getHoursDifference(mpToken.getCreateTime(), endDate) >= Convert.toLong(mpToken.getExpiresIn(), 7200L) * 1000) {
            // 未找到或超过两小时则实时获取
            RestTemplate restTemplate = new RestTemplate();
            String url = String.format(MpConstant.MP_ACCESS_TOKEN_URL, appId, appSecret);
            String json = restTemplate.getForObject(url, String.class);
            com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(json);
            if (jsonObject.getIntValue("errcode") != 0) {
                throw new RuntimeException(JSONObject.toJSONString(jsonObject));
            }
            Object accessToken = jsonObject.get("access_token");
            Object expiresIn = jsonObject.get("expires_in");

            if (mpToken == null) {
                mpToken = new BmsMpToken();
            }
            mpToken.setAppId(appId);
            mpToken.setExpiresIn(expiresIn.toString());
            mpToken.setAccessToken(accessToken.toString());
            mpToken.setCreateTime(endDate);
            if (ObjectUtils.isEmpty(mpToken.getId())) {
                baseMapper.insert(mpToken);
            } else {
                baseMapper.updateById(mpToken);
            }
        }

        return mpToken.getAccessToken();
    }

    private long getHoursDifference(Date startDate, Date endDate) {
        return endDate.getTime() - startDate.getTime();
    }
}
